/*
 * @lc app=leetcode.cn id=95 lang=typescript
 *
 * [95] 不同的二叉搜索树 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function generateTrees(n: number): Array<TreeNode | null> {
  if (n === 0) return [];

  const dfs = (l: number, r: number): Array<TreeNode | null> => {
    const result = [];
    if (l > r) {
      result.push(null);
      return result;
    }
    for (let i = l; i <= r; i++) {
      const leftTree = dfs(l, i - 1);
      const rightTree = dfs(i + 1, r);

      for (let left of leftTree) {
        for (let right of rightTree) {
          const root = new TreeNode(i, left, right);
          result.push(root);
        }
      }
    }
    return result;
  };

  return dfs(1, n);
}
// @lc code=end
